package com.wuhanins.insmytestdemo.app.activity;

import android.content.Context;
import android.os.Bundle;
import android.view.View;

import androidx.annotation.Nullable;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.baidu.location.LocationClient;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.wuhanins.common.utils.INSLog;
import com.wuhanins.common.utils.ToastUtil;
import com.wuhanins.core.promise.JPromiser;
import com.wuhanins.core.promise.Promiser;
import com.wuhanins.http.volley.WebApiVolleyHelper;
import com.wuhanins.http.volley.v3.IOnProxyDoneListener_v3;
import com.wuhanins.insmytestdemo.base.BaseActivity;
import com.wuhanins.insmytestdemo.databinding.ActivityLocationBinding;
import com.wuhanins.insmytestdemo.domainService.provider.MiPContext;
import com.wuhanins.insmytestdemo.extend.webApiProxy.insSysProxy.getCircleRangeProxy.GetCircleRangeOutput;
import com.wuhanins.insmytestdemo.extend.webApiProxy.insSysProxy.getCircleRangeProxy.GetCircleRangePInput;
import com.wuhanins.insmytestdemo.extend.webApiProxy.insSysProxy.getCircleRangeProxy.GetCircleRangeProxyApi;
import com.wuhanins.insmytestdemo.extend.webApiProxy.insSysProxy.getFenceRangeProxy.GetFenceRangeOutput;
import com.wuhanins.insmytestdemo.extend.webApiProxy.insSysProxy.getFenceRangeProxy.GetFenceRangePInput;
import com.wuhanins.insmytestdemo.extend.webApiProxy.insSysProxy.getFenceRangeProxy.GetFenceRangeProxyApi;
import com.wuhanins.zero.dialog.block.InsBlockUI;

import java.util.ArrayList;

/**
 * @author: Gab
 * @Project: fileService
 * @Pcakage: com.wuhanins.insmytestdemo.app.activity.BDLocationActivity
 * @Date: 2023年08月31日 09:28
 * @Description: 高德本地通过接口上传定位信息
 */
public class GDLocationActivity extends BaseActivity<ActivityLocationBinding> {

    private AMapLocationClient mAMapLocationClient;
    ArrayList<JPromiser> task;
    public LocationClient mLocationClient = null;
    private int scanSpanTime = 0;
    private String Radius = "50";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(ActivityLocationBinding.class);
    }

    @Override
    protected void iView() {
        try {
            mAMapLocationClient = new AMapLocationClient(getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void iData() {
        task = new ArrayList<>();
    }

    public void startLocation(View view) {
//        AMapLocationUtil mapLocationUtil = new AMapLocationUtil();
//        mapLocationUtil.startForLocation(mLocationClient, this, 1);
        startForLocation(mAMapLocationClient, this, 1);
//        BDLocation();
    }

    /**
     * 暂时禁用
     *
     * @param view
     */
    public void stopLocation(View view) {
        disableBackgroundLocation();
    }

    public void startRoundness(View view) {
        startRoundness(mAMapLocationClient, this, 1);
    }

    public void stopRoundness(View view) {
        disableBackgroundLocation();
    }

    public void disableBackgroundLocation() {
        if (mAMapLocationClient != null) {
            mAMapLocationClient.disableBackgroundLocation(true);
            mAMapLocationClient.stopLocation();
        }
    }

    public void startForLocation(AMapLocationClient mLocationClient, Context mAct, int monitorTime) {
        //初始化定位
//        mLocationClient = new AMapLocationClient(mAct.getApplicationContext());
//        mLocationClient.enableBackgroundLocation(2001, buildNotification(mAct));
        //设置定位回调监听
        task.clear();
        mLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                double sixLat = aMapLocation.getLatitude();
                double sixLon = aMapLocation.getLongitude();
                String address = aMapLocation.getAddress();
                if (address == null) {
                    address = "";
                }
                String sb = sixLat + "," + sixLon;
                if ("".equals(address)) {
                    sb = "";
                    ToastUtil.show(mAct, "定位出错");
                }
                String location = address;
                String nowDate = TimeUtils.date2String(TimeUtils.getNowDate());
                if (sixLat == 0 && sixLon == 0) {
                    return;
                }
                String resolve = "纬度: " + sixLat + "\n 经度: " + sixLon + "\n 时间: " + nowDate + "\n 地点: " + location;
                binding.tvLocation.setText(resolve);
//                Promiser fenceRange = getFenceRange("30.54228", "114.36204");

                Promiser promiser = Promiser.EMPTY();
                Promiser fenceRange = Promiser.EMPTY();
                Promiser q = Promiser.EMPTY();
                fenceRange = getFenceRange(String.valueOf(sixLat), String.valueOf(sixLon));
                q = new Promiser() {
                    @Override
                    protected void aync(Deffered<String, String> d) {
                        boolean safeString = getWallet().getSafeBoolean(WALLET_FENCE_RANGE);
                        ToastUtils.showLong(safeString ? "在范围内" : "不在范围内");
                        binding.tvScope.setText(safeString ? "圆形：当前坐标在范围内" : "当前坐标不在范围内");
                        d.resolve();
                    }
                };
                task.add(fenceRange);
                task.add(q);
                InsBlockUI.newInstance().$dialog(GDLocationActivity.this, task);

//                MainDomainService.getCreate(nowDate, sixLat, sixLon).run();
                INSLog.e("logan", "纬度:" + sixLat + " 经度:" + sixLon);
                INSLog.e("logan", "时间:" + nowDate);
                INSLog.e("logan", "地点:" + location);
            }
        });
        //声明AMapLocationClientOption对象
        //初始化AMapLocationClientOption对象
        final AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
        /**
         * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
         */
        mLocationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mLocationOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mLocationOption.setHttpTimeOut(2000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        if (monitorTime == 0) {
            mLocationOption.setInterval(10 * 1000 * 60);//可选，设置定位间隔。默认为10秒
        } else {
//            mLocationOption.setInterval(monitorTime);//可选，设置定位间隔。
            mLocationOption.setInterval(monitorTime * 1000 * 60);//可选，设置定位间隔。
        }
        mLocationOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mLocationOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
        mLocationOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mLocationOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mLocationOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mLocationOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        mLocationOption.setGeoLanguage(AMapLocationClientOption.GeoLanguage.DEFAULT);//可选，设置逆地理信息的语言，默认值为默认语言（根据所在地区选择语言）
        if (null != mLocationClient) {
            mLocationClient.setLocationOption(mLocationOption);
            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
            mLocationClient.stopLocation();
            mLocationClient.startLocation();
        }
    }

    public void startRoundness(AMapLocationClient mLocationClient, Context mAct, int monitorTime) {
        //初始化定位
//        mLocationClient = new AMapLocationClient(mAct.getApplicationContext());
//        mLocationClient.enableBackgroundLocation(2001, buildNotification(mAct));
        //设置定位回调监听
        task.clear();
        mLocationClient.setLocationListener(new AMapLocationListener() {
            @Override
            public void onLocationChanged(AMapLocation aMapLocation) {
                double sixLat = aMapLocation.getLatitude();
                double sixLon = aMapLocation.getLongitude();
                String address = aMapLocation.getAddress();
                if (address == null) {
                    address = "";
                }
                String sb = sixLat + "," + sixLon;
                if ("".equals(address)) {
                    sb = "";
                    ToastUtil.show(mAct, "定位出错");
                }
                String location = address;
                String nowDate = TimeUtils.date2String(TimeUtils.getNowDate());
                if (sixLat == 0 && sixLon == 0) {
                    return;
                }
                String resolve = "纬度: " + sixLat + "\n 经度: " + sixLon + "\n 时间: " + nowDate + "\n 地点: " + location;
                binding.tvLocation.setText(resolve);
//                Promiser fenceRange = getFenceRange("30.54228", "114.36204");

                Promiser fenceRange = getRoundness(String.valueOf(sixLat), String.valueOf(sixLon), "0");
                Promiser q = new Promiser() {
                    @Override
                    protected void aync(Deffered<String, String> d) {
                        boolean safeString = getWallet().getSafeBoolean(WALLET_ROUNDNESS);
                        ToastUtils.showLong(safeString ? "在范围内" : "不在范围内");
                        binding.tvScope.setText(safeString ? "圆形：当前坐标在范围内" : "当前坐标不在范围内");
                        d.resolve();
                    }
                };
                task.add(fenceRange);
                task.add(q);
                InsBlockUI.newInstance().$dialog(GDLocationActivity.this, task);

                INSLog.e("logan", "纬度:" + sixLat + " 经度:" + sixLon);
                INSLog.e("logan", "时间:" + nowDate);
                INSLog.e("logan", "地点:" + location);
            }
        });
        //声明AMapLocationClientOption对象
        //初始化AMapLocationClientOption对象
        final AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
        /**
         * 设置定位场景，目前支持三种场景（签到、出行、运动，默认无场景）
         */
        mLocationOption.setLocationPurpose(AMapLocationClientOption.AMapLocationPurpose.SignIn);
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);//可选，设置定位模式，可选的模式有高精度、仅设备、仅网络。默认为高精度模式
        mLocationOption.setGpsFirst(false);//可选，设置是否gps优先，只在高精度模式下有效。默认关闭
        mLocationOption.setHttpTimeOut(2000);//可选，设置网络请求超时时间。默认为30秒。在仅设备模式下无效
        if (monitorTime == 0) {
            mLocationOption.setInterval(10 * 1000 * 60);//可选，设置定位间隔。默认为10秒
        } else {
//            mLocationOption.setInterval(monitorTime);//可选，设置定位间隔。
            mLocationOption.setInterval(monitorTime * 1000 * 60);//可选，设置定位间隔。
        }
        mLocationOption.setNeedAddress(true);//可选，设置是否返回逆地理地址信息。默认是true
        mLocationOption.setOnceLocation(false);//可选，设置是否单次定位。默认是false
        mLocationOption.setOnceLocationLatest(false);//可选，设置是否等待wifi刷新，默认为false.如果设置为true,会自动变为单次定位，持续定位时不要使用
        AMapLocationClientOption.setLocationProtocol(AMapLocationClientOption.AMapLocationProtocol.HTTP);//可选， 设置网络请求的协议。可选HTTP或者HTTPS。默认为HTTP
        mLocationOption.setSensorEnable(false);//可选，设置是否使用传感器。默认是false
        mLocationOption.setWifiScan(true); //可选，设置是否开启wifi扫描。默认为true，如果设置为false会同时停止主动刷新，停止以后完全依赖于系统刷新，定位位置可能存在误差
        mLocationOption.setLocationCacheEnable(true); //可选，设置是否使用缓存定位，默认为true
        mLocationOption.setGeoLanguage(AMapLocationClientOption.GeoLanguage.DEFAULT);//可选，设置逆地理信息的语言，默认值为默认语言（根据所在地区选择语言）
        if (null != mLocationClient) {
            mLocationClient.setLocationOption(mLocationOption);
            //设置场景模式后最好调用一次stop，再调用start以保证场景模式生效
            mLocationClient.stopLocation();
            mLocationClient.startLocation();
        }
    }

    public final static String WALLET_FENCE_RANGE = "BDLocationActivity.getFenceRange_data";
    public final static String WALLET_ROUNDNESS = "BDLocationActivity.getRoundness_data";

    public Promiser getFenceRange(String Lat, String Lon) {
        GetFenceRangeProxyApi proxyApi = new GetFenceRangeProxyApi(MiPContext.getInstance());
        GetFenceRangePInput input = new GetFenceRangePInput();
        input.setLatitude(Lat);
        input.setLongitude(Lon);
        return proxyApi.$doRequest(WebApiVolleyHelper.sharedRequestQueue(), input, new IOnProxyDoneListener_v3<GetFenceRangeOutput>() {
            @Override
            public void done() {

            }

            @Override
            public boolean error(int code, String message, int type) {
                return false;
            }

            @Override
            public void success(GetFenceRangeOutput getFenceRangeOutput) {
                getWallet().putExtra(WALLET_FENCE_RANGE, getFenceRangeOutput.getContent());
            }
        });
    }

    public Promiser getRoundness(String Lat, String Lon, String Radius) {
        GetCircleRangeProxyApi proxyApi = new GetCircleRangeProxyApi(MiPContext.getInstance());
        GetCircleRangePInput input = new GetCircleRangePInput();
//        input.setLatitude1(30.54238);
        input.setCurrentLatitude(Double.parseDouble(Lat));
//        input.setLongitude1(114.36210);
        input.setCurrentLongitude(Double.parseDouble(Lon));
        input.setCircleLatitude(30.54261);
        input.setCircleLongitude(114.36177);
        input.setRadius(Radius);
        return proxyApi.$doRequest(WebApiVolleyHelper.sharedRequestQueue(), input, new IOnProxyDoneListener_v3<GetCircleRangeOutput>() {
            @Override
            public void done() {

            }

            @Override
            public boolean error(int code, String message, int type) {
                return false;
            }

            @Override
            public void success(GetCircleRangeOutput getCircleRangeOutput) {
                getWallet().putExtra(WALLET_ROUNDNESS, getCircleRangeOutput.getContent());
            }
        });
    }
}